<?php


namespace api\app\controller;


use api\app\model\UserModel;
use api\app\validate\UserValidate;
use cmf\controller\RestBaseController;

class LoginController extends RestBaseController
{
    //注册
    public function register()
    {
        $data = input('post.');
        $validate = new UserValidate();
        $res = $validate->scene('register')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if ($user){
            $this-> error('该用户已被注册');
        }
        $c = checkCode($data['mobile'],$data['code']);
        if (!$c){
            $this->error('验证码错误');
        }
        $data['create_time'] = time();
        $data['money'] = 0;
        if (UserModel::create($data)){
            $this->success('注册成功');
        }


    }
    //登录
    public function login()
    {
        $data = input('post.');
        $validate = new UserValidate();
        $res = $validate->scene('login')->check($data);
        if (!$res){
            $this->error($validate->getError());
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if (!$user){
            $this-> error('该用户未注册');
        }
        $c = checkCode($data['mobile'],$data['code']);
        if (!$c){
            $this->error('验证码错误');
        }
        $token = createToken($user['id'],$user['mobile']);
        $this->success('登录成功',[
            'token' => $token
        ]);

    }
    //发送验证码
    public function SmsCode()
    {
        $mobile = input('post.mobile');
        return SendCode($mobile);
    }
}